"""
@ProjectName : StudentManagementSystem
@File        : student_db.py
@Author      : WorldWind(1772830365@qq.com)
@Address     : ChangSha - BoWeiFeng
@Date        : 2025/7/16 上午11:27
"""
from students.student import Student
from utils.DBUtil import Database


# 数据库连接
class StudentDB:
    def __init__(self):
        print(f'This is __init__ method. {self.get_class_name()} class startup')
        host = '127.0.0.1'
        port = 3306
        user = 'root'
        passwd = 'root'
        db = 'students'
        # 插入一条数据
        self.dbObj, self.cursor = Database.openDB(host, port, user, passwd, db)

    # 删除学生(根据学号删除学生)
    def delete(self, sno):
        sql = f"DELETE FROM t_student WHERE sno = '{sno}'"
        result = Database.writeDB(sql, self.cursor)
        self.dbObj.commit()
        return result

    # 添加一个学生,这里的student是一个对象
    def add(self, student):
        sql = f"INSERT INTO t_student(sno,name,age,phone,address,sex) VALUES ('{student.sno}','{student.name}',{student.age},'{student.phone}','{student.address}','{student.sex}')"
        result = Database.writeDB(sql, self.cursor)
        self.dbObj.commit()
        return result

    # 更新学生信息
    def update(self, student):
        sql = (f"UPDATE t_student SET "
               f"sno='{student.sno}',name='{student.name}',age={student.age},phone='{student.phone}',address='{student.address}' "
               f"WHERE id={student.id}")
        result = Database.writeDB(sql, self.cursor)
        self.dbObj.commit()
        return result

    # 根据学号,姓名查询学生信息
    def search(self, sno=None, name=None):
        if sno != None:
            sql = f"SELECT * FROM t_student WHERE sno = '{sno}'"
        if name != None:
            sql = f"SELECT * FROM t_student WHERE name = '{name}'"
        result = Database.readAll(sql, self.cursor)
        return result

    @classmethod
    def get_class_name(cls):
        return cls.__name__

    def __del__(self):
        Database.closeDB(self.dbObj)
        print(f'This is __del__ method. The {self.get_class_name()} class has been recycled')


if __name__ == '__main__':
    stu = StudentDB()
    # stu.delete('s005')
    # s1 = Student()
    # s1.sno = 's005'
    # s1.name = '李明'
    # s1.age = 18
    # s1.sex = '女'
    # s1.phone = '18845729136'
    # s1.address = 'China XiAn'
    # s1.id = 5
    # stu.update(s1)
    # stu.add(s1)
    print(stu.search(sno='s005'))
